/******************************************************************************
 * WSS List Item Object Class by Samir Sijercic 3/27/2009
 * 
 * Way to call from form view web part from jPoint.js:
 
 <script type="text/javascript" src="/eon/com/res/jPointFormListItem.js" ></script> 
 
 //Way#1: Calling the constructor
 var myWSSListItem = new jPointFormListItem();

 *
 ******************************************************************************/
//Constructor
/*This is what the comments Node looks like for xxxxForm.aspx pages
<TD valign="top" class="ms-formbody" width="400px">
<!-- FieldName="Title"
     FieldInternalName="Title"
     FieldType="SPFieldText"
-->
This is what the comments div looks like for other pages because readForm2 from jPoint inserts this node
<TD valign="top" class="ms-formbody" width="400px">
<div class="commentsNode" style="display: none">
    FieldName="Title"
    FieldInternalName="Title"
    FieldType="SPFieldText"
</div>
*/
function jPointFormListItem(SPFieldCommentsNode) 
{
	$.logfunction("jPointFormListItem("+SPFieldCommentsNode+") Enter Constructor");
	try
	{
		//Internal global variables
		var FieldInternalName = "FieldInternalName";
		var FieldName = "FieldName";
		var FieldType = "FieldType";
		//Properties
		this.FieldInternalName = FieldInternalName;
		this.FieldName = FieldName;
		this.FieldType = FieldName;
		this.Item = $(SPFieldCommentsNode.parentNode).find("span").get(0);   //more generic than childNodes[1] - does not work for non xxxxform.aspx pages;
		//Get entire SPItem row on page
		this.ItemRow = SPFieldCommentsNode.parentNode.parentNode;
		//Object Methods are declared below function definitions
		
		//Populating Property Fields
		var r = new RegExp("\"");
		var textsplitter = SPFieldCommentsNode.innerHTML.split(r);
		var textitemsplitter = null;
		//Potential area for optimization		
		for (var i=0;i < textsplitter.length; i++ )
		{
		//Try to find attribute strings
		textitemsplitter = textsplitter[i].split("=");
			
		if(textitemsplitter.length > 0)
		{
		//Find type of attribute (Internal Name, Field Name or Field Type)
		if(textitemsplitter[0].indexOf(FieldInternalName) >= 0)
		{
		this.InternalName = textsplitter[i+1];
		}
		else if(textitemsplitter[0].indexOf(FieldName) >= 0)
		{
		this.Name= textsplitter[i+1];		
		}
		else if(textitemsplitter[0].indexOf(FieldType) >= 0)
		{
		this.Type= textsplitter[i+1];
		}
		}
		}
		$.loginfo("InternalName:" + this.InternalName + " Name:" + this.Name + " Type:" + this.Type);
		//Private functions
		/*
		* name: Hide
		* purpose: hide entire row of the form element
		* input: none
		* visibility: public
		* return: this
		*/
	   	function Hide()	
	   	{
	   		$.logfunction("Hide() Method");
			this.ItemRow.style.display="none";
			return this;
		}
		/*
		* name: Show
		* purpose: show entire row of the form element
		* input: none
		* visibility: public
		* return: this
		*/
		function Show()
		{
			$.logfunction("Show() Method");
			this.ItemRow.style.display="";
			return this;
		}
		/*
		* name: getValue
		* purpose: get the value of the form input element for the selected row
		* input: none
		* visibility: public
		* return: void
		*/
		function getValue()
		{
			$.logfunction("getValue() Enter Method");
			try
			{
			   	var val = '';
			    $.loginfo("Type:" + this.Type);
				switch(this.Type)
			   	{
			    	case "SPFieldUser": //people picker
				      	//Check for browser compatibility
				      	if(!browseris.ie5up || !browseris.win32 || IsAccessibilityFeatureEnabled())
				      	{
				      		//Get Text Area and set its value
				      		val = $(this.Item).find('textarea').attr('value');
				          	
				        }
				        else
				        {
				        	//Set html value of ms-inputuserfield
				        	$(document).ready(function() {
								val = $(this.Item).find('.ms-inputuserfield').html();
							});
							
						}
			      	break;
			      	case "SPFieldBoolean": //checkbox
			        	val = $(this.Item).find("[type='checkbox']").get(0).checked;
			      	break;
				  	case "SPFieldDateTime": //Date and time field
					  	val = $(this.Item).find('input:text').val();
					    val += ' ';
					   	val += $(this.Item).find('select:eq(0)').val();
					   	val += $(this.Item).find('select:eq(1)').val();
					break;
					case "SPFieldNumber": //Fixing percent field
						val = $(this.Item).find("[title='"+this.Name+"']").get(0).value;
					 	if(this.InternalName.toLowerCase().indexOf("percent") >= 0)
					 		val = val/100;
				 	break;
				 	case "SPFieldNote":
				 		if($(this.Item).find('.ms-rtelong').contents().find('body').html() != null)
				 		{
				 			val = $(this.Item).find('.ms-rtelong').contents().find('body').html();
				 		}
				 		else
				 		{
				 			//var textAreaVal = $(this.Item).find('textarea').get(0).firstChild.nodeValue;
				 			val = $(this.Item).find('textarea:eq(0)').text();//$(textAreaVal).get(0).innerHTML;
				 			
				 			if(val.length == 0)
					 		{
					 			val = $(this.Item).find('textarea:eq(0)').get(0).innerHTML;
					 		}
				 		}
				 		
				 	break;
				 	case "SPFieldChoice":
				 		var radioBtn = $(this.Item).find('input[type="radio"]:eq(1)');
				 		//This is for choice field with alternate text field
				 		if(radioBtn.get(0) != null && radioBtn.get(0).checked)
				 		{
				 			val = $(this.Item).find('input[type="text"]:eq(0)').val();
				 		}
				 		else
				 		{
				 			val = $(this.Item).find('select:eq(0)').val();
				 		}
				 	break;
				 	case "SPFieldLookupMulti":
				 		val = '';
				 		if($(this.Item).find('img').length > 0){
							var inpt = $(this.Item).find('.ms-lookuptypeintextbox');
							val = $('#' + inpt.attr('optHid')).val() + ';#' + inpt.val();
						}else{
							var opt = $(this.Item).find("SELECT")[1]; //Get last input of the field
							for(var i=0; i<opt.options.length; i++)
							{
								if(i == 0) val += opt[i].value + ';#' + opt[i].text;
								else val += ';#' + opt[i].value + ';#' + opt[i].text;
							}
						}
				 	break;
				 	case "SPFieldMultiChoice":
				 		val = '';
				 		var field = $(this.Item)
				 			field.find('.ms-RadioText').each(function(){
							if($(this).find('input:eq(0)').attr('checked')){
								if($(this).text().toUpperCase() != "SPECIFY YOUR OWN VALUE:")
								{
									if(val == '') val = $(this).text();
									else val += ';#' + $(this).text();
								}
								else
								{
									field.find('INPUT').each(function(){
										if(this.type == "text")
										{
											if(val == '') val = $(this).val();
											else val += ';#' + $(this).val();
										} 
									});
								}
							}
						});
				 	break;
			     	default: //all other fields are not as irregular and are taken care of with below statement
			      		val = $(this.Item).find("[title='"+this.Name+"']").get(0).value; //finds the first element within the span that matches on title and retrieves that DOM element's value.    
			      	break;
			    }
		    }
			catch(err)
			{
				$.log("getValue Error:" + err);
			}
			$.loginfo("return value:" + val);
		    $.logfunction("getValue() Exit Method");
		    return val;
		}
		/*
		* name: setValue
		* purpose: set the value of the form input element for the selected row
		* input: none
		* visibility: public
		* return: void
		*/
		function setValue(value)	
		{
			$.logfunction("setValue("+value+") Enter Method")
			try
			{
				//Error out if user has not set up setValue properly in code
				if(this.Type == null)
				{
					this.Error = "Please use following as example to set field value: var spItem = myWSSList.getItem('Title'); spItem.setValue('some value');"	
					return this;
				}
			
			   var val = "";
			   if (value != undefined)
			   {
			     val = value;
			   }
			   else
			   {
			     this.Error = "Passing an undefined value to setValue function is not permitted.";
			     return this; 
			   }
				$.loginfo("Type:" + this.Type);
			   //Check field type
			   switch(this.Type)
			   {
			      case "SPFieldUser":       	
			      
			      	//Check for browser compatibility
			      	if(!browseris.ie5up || !browseris.win32 || IsAccessibilityFeatureEnabled())
			      	{
			      		//Get Text Area and set its value
			          	var textArea = $(this.Item).find('textarea');
			      	
			          	textArea.attr('value', value);
			        }
			        else
			        {
			        	//Set html value of ms-inputuserfield
			            $(document).ready(function() {
							$(this.Item).find('.ms-inputuserfield').html(value);
						});
						
					}
					
					//Get check names button and perform click
					$(document).ready(function() {
						$(this.Item).find('[title=Check Names]').click();
					});		
			      break;
			      
			     case "SPFieldBoolean": //checkbox
			        val = jQuery(this.Item).find("[type='checkbox']").get(0).checked = val;
			      break;
			
				 case "SPFieldNote": //Ritch text editor
					{		
						$(this.Item).find('textarea:eq(0)').text(val);
						$(this.Item).find('.ms-rtelong').contents().find('body').html('<div>' + val + '</div>');
					}
				  break;
				  case "SPFieldDateTime": //Date and time field
				  	 var sep = value.split(' ');
				  	 $(this.Item).find('input:eq(0)').val(sep[0]);
					 //Check for time part of the date time
					 if(sep.length > 1)
					 {
					  sep = sep[1].split(':');
					  if(sep[0].toString().length == 1) sep[0] = '0' + sep[0];
					   sep[0] += ':';
					   $(this.Item).find('select:eq(0)').val(sep[0]);
					   $(this.Item).find('select:eq(1)').val(sep[1]);
					  }
					  else
					  {
					   $(this.Item).find('select:eq(0)').val("00:");
					   $(this.Item).find('select:eq(1)').val("00");
					  }
				  	break;
					case "SPFieldLookupMulti":
						if($(this.Item).find('img').length == 0)
						{
							var options = $(this.Item).find("SELECT")[1];
							var options2 = $(this.Item).find("SELECT")[0];
							var optionslength = options.length;
							for(var i=0; i< optionslength; i++)
							{
								var myNewOption = new Option(options[0].text, options[0].value);
								options2.add(myNewOption); //Adding values back to lookup list
								options.remove(0);
							}
						}
				  		else
				  		{
					  		var $inpt = $(this.Item).find('.ms-lookuptypeintextbox');
					  		var sep = $inpt.attr('choices').split('|');
					  		for(var i=0; i<sep.length; i+=2)
					  		{
						  		if(sep[i+1] == val)
						  		{
							  		$inpt.val(sep[i]); break;
						  		}
					  		}
					  		$('#' + $inpt.attr('optHid')).val(val);
				  		}
				  	break;
				  	case "SPFieldChoice":
				  		$(this.Item).find('select:eq(0)').val(val);
				  		var radioBtn1 = $(this.Item).find('input[type="radio"]:eq(0)');
				  		var radioBtn2 = $(this.Item).find('input[type="radio"]:eq(1)');
				  		if(radioBtn1.get(0) != null && $(this.Item).find('select:eq(0)').val() == val)
				  		{
				  			radioBtn1.get(0).checked = true;
				  			$(this.Item).find('input[type="text"]:eq(0)').val('');
				  		}
				 		else if(radioBtn2.get(0) != null && $(this.Item).find('select:eq(0)').val() != val) //This is for choice field with alternate text field
				 		{
				 			radioBtn2.get(0).checked = true;
				 			$(this.Item).find('input[type="text"]:eq(0)').val(val);
				 		}
				  	break;
				  	case "SPFieldMultiChoice": //List of checkboxes with specify your own value text box
				  		var field = $(this.Item)
				 			field.find('.ms-RadioText').each(function(){
				 			if($(this).find('input:eq(0)').attr('checked')){
				 				if(val == '') //This is statement for clearForm()
				 				{
					 				this.firstChild.checked = false
									if($(this).text().toUpperCase() == "SPECIFY YOUR OWN VALUE:")
									{
										field.find('INPUT').each(function(){
											if(this.type == "text")
											{
												$(this).val('');
											} 
										});
									}
								}
							}
						});
				 	break;

			     default: //all other fields are not as irregular and are taken care of with below statement
			     	if(jQuery(this.Item).find("[title='"+this.Name+"']") != null)
			     	{
			        	val = jQuery(this.Item).find("[title='"+this.Name+"']").get(0).value = val; //finds the first element within the span that matches on title and retrieves that DOM element's value.    
			        }
			        else
			        {
			        	this.Error = this.Name + "does not exist.";
			
			        }
			      break;
			     
			    }
			    this.Error = "Successfully set the value.";
		    }
			catch(err)
			{
				$.log("setValue Error:" + err);
			}
		    $.logfunction("setValue() Exit Method");
		    return this;	
		}
		/*
		* name: populateDropDown
		* purpose: set the dropdown list options
		* input: jSON object with title/value pairs, title field (string), value field (string)
		* visibility: public
		* return: newly created/modified drop down object
		*/
		function convertandPopulateDropDown(values, text_field, value_field)
		{
			$.logfunction("convertandPopulateDropDown("+values+", "+text_field+", "+value_field+") Enter Method");
			var opt = null;
			var dropdownobj = null;
			try
			{
				var textfieldobj = $(this.Item).find("input");
				//Only allow text field to be converted
				if(textfieldobj.get(0) != null)
				{
					$.loginfo("Hide the text field");
					textfieldobj.hide();
					//Create new drop down
					if($(this.Item).find("SELECT").get(0) == null)
					{
						$.loginfo("Create dropdown");
						dropdownobj = document.createElement("SELECT");
						dropdownobj.id = this.InternalName + "_ddl";
						dropdownobjonChange = new Function("e", "$(this.parentNode).find('input').get(0).value=this.options[this.selectedIndex].value;");
						$(this.Item).get(0).insertBefore(dropdownobj, $(this.Item).get(0).firstChild);
						dropdownobj.onchange=dropdownobjonChange;
					}
					else //found existing drop down
					{
						$.loginfo("Found dropdown already in this form field");
						dropdownobj = $(this.Item).find("SELECT").get(0);
					}
					
					var dropdownlength = dropdownobj.options.length;
					$.loginfo("Clear drop down");
					//Clear all current values of the drop down
					for (var i=0;i<dropdownlength;i++)
					{
						dropdownobj.options[0]=null;
			   		}
			   		$.loginfo("Populate drop down");
			   		//Populate drop down with new values
					$.each(values, function(idx, dropdown){
						//Create new option element
						opt = document.createElement("option");
						//Get values for text/value attributes of option field
						var ddltext = $(dropdown).attr('ows_' + text_field);
						var ddlvalue = $(dropdown).attr('ows_' + value_field);
						//Make sure text/value attributes exist
						if(ddltext != null && ddlvalue != null)
						{
					        // Add an Option object to Drop Down/List Box
					        dropdownobj.options.add(opt);        // Assign text and value to Option object
					        opt.text = ddltext;
					        opt.value = ddlvalue;
					        $.loginfo("Add option text:"+ddltext+" value:"+ddlvalue);	        	
				        }
				        else
				        {
				        	if(ddltext == null)
				        		$.log("textfield:'" + text_field + "' does not exist in the jQuery object!", 1);
				        	else
				        		$.log("valuefield:'" + value_field + "' does not exist in the jQuery object!", 1);
				        }
					});
					//Select drop down value to match text box value
					if(textfieldobj.get(0).value.length > 0)
					{
						var bFound = false;
						for(var i=0; i<dropdownobj.options.length; i++)
						{
							if(dropdownobj.options[i].value.toUpperCase() ==  textfieldobj.get(0).value.toUpperCase())
							{
								bFound = true;
								dropdownobj.selectedIndex = dropdownobj.options[i].index;
								break;
							}
						}
						//If textfield value is not found in drop down add it to drop down and select
						if(!bFound)
						{
							opt = document.createElement("option");
							dropdownobj.options.add(opt);        // Assign text and value to Option object
					        opt.text = textfieldobj.get(0).value;
					        opt.value = textfieldobj.get(0).value;
					        dropdownobj.selectedIndex = opt.index;
						}
							
					}
					else
					{
						//Set default value to first item
						if(dropdownobj.options.length > 0)
							textfieldobj.get(0).value = dropdownobj.options[dropdownobj.selectedIndex].value;
					}
					
				}
				else
				{
					alert("Error in convertandPopulateDropDown, jQuery object 'values' is not of type input!");
				}
			}
			catch(err)
			{
				$.log("convertandPopulateDropDown Error:" + err);			
			}
			$.logfunction("convertandPopulateDropDown() Exit Method");
			return dropdownobj;
		}
	
		//Object Methods	
		this.hide = Hide;
		this.show=Show;
		this.getValue=getValue;
		this.setValue=setValue;
		this.convertandPopulateDropDown=convertandPopulateDropDown;
	
		
	}
	catch(err)
	{
		$.log("jPointFormListItem Error:" + err);
	}

	$.logfunction("jPointFormListItem() Exit Constructor");
}
